package ThreadTest;

import java.util.Random;

public class ProductTest {
    public static void main(String[] args) {
        Clerk clerk = new Clerk(10);
        Thread thread = new Thread(new Producer(clerk));
        Thread thread1 = new Thread(new Consumer(clerk));
        thread.setName("生产者");
        thread1.setName("消费者");
        thread.start();
        thread1.start();
    }
}
// 生产者
class Producer implements Runnable{
    private Clerk clerk;
    public Producer(Clerk clerk) {
        this.clerk = clerk;
    }
    @Override
    public void run() {
        while (true){
            try {
                Thread.sleep(new Random().nextInt(500));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            clerk.product();
        }
    }
}
// 消费者
class Consumer implements Runnable{
    private Clerk clerk;

    public Consumer(Clerk clerk) {
        this.clerk = clerk;
    }

    @Override
    public void run() {
        while (true){
            try {
                Thread.sleep(new Random().nextInt(500));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            clerk.consume();
        }
    }
}

// 柜台
class Clerk{
    private int productCount;
    public Clerk(int productCount){
        this.productCount = productCount;
    }
    // 开始生产
    public synchronized void product()  {
        if(productCount < 20 ){
            this.productCount++;
            System.out.println(Thread.currentThread().getName()+"::开始生产第"+productCount+"产品");
            notify();
        }else {
            // 生产过度，开始等待
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    // 开始消费
    public synchronized void consume()  {
        if(productCount > 0 ){
            System.out.println(Thread.currentThread().getName()+"::开始消费第"+productCount+"产品");
            this.productCount--;
            notify();
        }else {
            // 消费过度，开始等待
            try {
                wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }


}
